<template>
	<view class="container">
		<!-- 垂直滑动容器 -->
		<swiper class="swiper" vertical :current="current" @change="onSwiperChange" :disable-touch="loading">
			<swiper-item v-for="(item, index) in videoList" :key="item.id">
				<video
					:id="`video-${index}`"
					class="video"
					:src="item.video"
					:autoplay="current === index"
					:muted="muted"
					:controls="true"
					:loop="true"
					@click="togglePlay"
					@play="onPlay(index)"
					@pause="onPause"
				/>
				<!-- 视频元信息 -->
				<view class="right-controls flex flex-col items-center justify-between">
					<view class="item flex flex-col items-center" @click="hits(item.id, item.is_hit, index)">
						<image :src="item.is_hit == 1 ? '/static/video/ic_dspdzan@2x.png' : '/static/video/ic_dspdzanwei@2x.png'" class="icon"></image>
						<view class="val">{{ item.hits }}</view>
					</view>
					<view class="item flex flex-col items-center" @click="commentShowPopup(item.id)">
						<image src="/static/video/ic_dspplun@2x.png" class="icon"></image>
						<view class="val">{{ item.comments }}</view>
					</view>
					<view class="item flex flex-col items-center" @click="collects(item.id, item.is_collect, index)">
						<image :src="item.is_collect == 1 ? '/static/video/ic_dspscang@2x.png' : '/static/video/ic_dspscangwei@2x.png'" class="icon"></image>
						<view class="val">{{ item.collects }}</view>
					</view>
				</view>

				<view class="user-info flex flex-col">
					<view class="product flex" v-show="item.product">
						<image :src="item.product?.icon" class="icon"></image>
						<view class="right flex flex-1 flex-col justify-between">
							<view class="title line-1-clamp">{{ item.product?.title }}</view>
							<view class="price-box flex">
								<view class="price rmb">{{ item.product?.vip_price }}</view>
								<view class="decoration">￥{{ item.product?.price }}</view>
							</view>
						</view>
					</view>

					<view class="video-desc line-3-clamp">{{ item.describe }}</view>

					<view class="user flex items-center" v-show="item.video_type == 1">
						<image :src="item.user?.photo" class="photo"></image>
						<view class="nickname">{{ item.user?.nickname }}</view>
						<view class="date">· {{ item.create_date }}</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		<view class="touch-overlay" v-if="overlay"></view>
	</view>
	<up-popup :show="commentShow" @close="commentShowClose()" :round="20" :customStyle="{ height: '70vh' }">
		<view class="comment">
			<view class="comment-title">
				评论
				<text>({{ commentCount }})</text>
			</view>
			<scroll-view :scroll-top="0" :scroll-y="true" class="scroll-Y" @scrolltolower="scrolltolower" @touchmove.stop>
				<view class="comment-list" style="height: 60vh">
					<up-skeleton :loading="loadStatus" avatar rows="3" style="margin-top: 30rpx"></up-skeleton>
					<view v-if="!loadStatus">
						<view class="item flex" v-for="(item, index) in commentList" v-if="commentList.length > 0">
							<image :src="item.user?.photo" class="photo"></image>
							<view class="right flex-1">
								<view class="nickname">
									<text>{{ item.user?.nickname }}</text>
									<text class="author" v-show="item.is_author == 1">作者</text>
								</view>
								<view class="content">{{ item.content }}</view>
								<view class="images flex items-center" v-show="item.images">
									<up-image
										class="ch"
										radius="10rpx"
										v-for="(item, index) in item.images.split(',')"
										:show-loading="true"
										:src="item"
										width="80px"
										height="80px"
										bgColor="transparent"
										@click="showPreviewImage([item])"
									></up-image>
								</view>
								<!-- <view class="re-time flex items-center">
									<view class="time">{{ item.create_time }}</view>
									<view class="replay" @click="replay(item.id, 0, item.user?.nickname)">回复</view>
								</view> -->

								<view class="replay-box" v-for="(last, index) in item.reply">
									<view class="item flex">
										<image :src="last.user?.photo" class="photo"></image>
										<view class="right flex-1">
											<view class="nickname flex">
												<text>{{ last.user?.nickname }}</text>
												<text class="author" v-show="last.is_author == 1">作者</text>
												<view class="flex items-center replay-next" v-show="last.responder_id > 0">
													<up-icon name="play-right-fill" size="15" class="icon"></up-icon>
													<view class="replay-nickname">{{ last.responder?.nickname }}</view>
												</view>
											</view>
											<view class="content">{{ last.content }}</view>
											<!-- <view class="re-time flex items-center">
												<view class="time">{{ last.create_time }}</view>
												<view class="replay" @click="replay(item.id, last.user?.id, last.user?.nickname)">回复</view>
											</view> -->
										</view>
									</view>
								</view>
							</view>
						</view>

						<up-empty mode="data" text="暂无评论" marginTop="50%" v-else></up-empty>
					</view>
				</view>
			</scroll-view>
			<view class="replay-con" @click="launchComment()">
				<view class="chn flex items-center justify-between">
					<view class="tips">发起评论~</view>
					<view class="icons flex items-center">
						<!-- <image src="/static/video/ic_piuntup@2x.png" class="icon"></image> -->
						<image src="/static/video/ic_plunsrbiaoq@2x.png" class="icon"></image>
					</view>
				</view>
			</view>
		</view>
	</up-popup>

	<up-popup :show="commentReplayShow" @close="commentReplayShow = false" :round="20">
		<view class="comment-text">
			<view class="fill">
				<textarea v-model="formRef.content" class="inp" placeholder-class="inp-place" :placeholder="commentNickname"></textarea>
				<!-- <Upload v-model="files" :maxCount="5" @change="handleChange" @success="handleSuccess" @error="handleError" @delete="handleDelete" /> -->
			</view>
			<view class="fun-fill flex items-center justify-between">
				<!-- <view class="icons flex items-center">
					<image src="/static/video/ic_piuntup@2x.png" class="icon"></image>
				</view> -->
				<view class="btn" @click="submitComment">发表</view>
			</view>
		</view>
	</up-popup>
</template>

<script setup>
	import { ref, onMounted, onUnmounted } from 'vue';
	import { port, hint, showPreviewImage } from '/service/port';
	import { onShow, onHide, onReachBottom } from '@dcloudio/uni-app';
	import Upload from '/components/Uploads.vue';
	// 创建响应式数据
	const commentShow = ref(false);
	const commentPage = ref(1);
	const commentList = ref([]);
	const commentCount = ref(0);
	const commentNickname = ref('请填写要发表的评论');
	const overlay = ref(false);
	const commentReplayShow = ref(false);
	const loadStatus = ref(true);
	// 视频列表数据
	const videoList = ref([]);
	const current = ref(0);
	const manualPaused = ref(false);
	const loading = ref(false);
	const muted = ref(false);
	const pageSize = 5;
	let videoContexts = {};
	const swiperKey = ref(0);
	const playingIndex = ref(-1);

	function replay(comment_id, responder_id, nickname) {
		commentReplayShow.value = true;

		formRef.value.comment_id = comment_id;
		formRef.value.responder_id = responder_id;
		commentNickname.value = '回复@' + nickname;
	}

	async function hits(id, is_hits, index) {
		let res = await port('videoHit', { id: id, status: is_hits == 1 ? 0 : 1 });
		setTimeout(() => {
			hint(res.msg);
			videoList.value[index].is_hit = is_hits == 1 ? 0 : 1;
			videoList.value[index].hits += is_hits == 1 ? -1 : 1;
		}, 100);
	}

	async function collects(id, is_collect, index) {
		let res = await port('videoCollect', { id: id, status: is_collect == 1 ? 0 : 1 });
		setTimeout(() => {
			hint(res.msg);
			videoList.value[index].is_collect = is_collect == 1 ? 0 : 1;
			videoList.value[index].collects += is_collect == 1 ? -1 : 1;
		}, 100);
	}

	async function commentShowPopup(id) {
		openPlay(false);
		commentShow.value = true;
		formRef.value.id = id;
		getVideoComments(id);
	}

	async function getVideoComments(id) {
		let res = await port('getVideoComments', { id: id, page: commentPage.value });
		setTimeout(() => {
			loadStatus.value = false;
			if (res.data.length) {
				commentList.value = [...commentList.value, ...res.data];
				commentCount.value = res.count;
			}
		}, 500);
	}

	async function submitComment() {
		let res = await port('submitComment', formRef.value);

		setTimeout(() => {
			hint(res.msg);
			videoList.value[current.value].comments += 1;
			commentReplayShow.value = false;

			formRef.value.content = '';
			formRef.value.images = '';
			commentList.value.length = 0;
			files.value.length = 0;
			commentPage.value = 1;
			loadStatus.value = true;
			getVideoComments(videoList.value[current.value].id);

			formRef.value.responder_id = '';
			commentNickname.value = '请填写要发表的评论';
		}, 100);
	}

	function launchComment() {
		commentReplayShow.value = true;
	}

	function commentShowClose() {
		commentShow.value = false;
		commentList.value.length = 0;
		commentPage.value = 1;
		openPlay(true);
	}

	function scrolltolower() {
		commentPage.value += 1;
		getVideoComments(videoList.value[current.value].id);
	}

	const files = ref([]);

	const formRef = ref({
		id: '',
		content: '',
		images: '',
		video: '',
		responder_id: '',
		comment_id: ''
	});

	const handleChange = (event) => {
		const images = files.value.map((i) => {
			return i.url;
		});
		formRef.value.images = images.length > 0 ? images.join(',') : '';
	};

	// 生命周期
	onMounted(() => {
		loadVideos();
	});

	onUnmounted(() => {
		clearAllVideoContexts();
	});

	onShow(() => {
		if (!manualPaused.value) {
			playCurrentVideo();
		}
	});

	onHide(() => {
		pauseCurrentVideo();
	});

	const onPlay = (index) => {
		playingIndex.value = index;
		manualPaused.value = false;

		videoList.value.forEach((_, i) => {
			if (i !== index && getVideoContext(i).paused === false) {
				getVideoContext(i).pause();
			}
		});
	};

	const onPause = () => {
		if (!manualPaused.value && process.env.UNI_PLATFORM === 'mp-weixin') {
			setTimeout(() => getVideoContext(current.value).play(), 200);
		}
	};

	const openPlay = (open) => {
		const ctx = getVideoContext(current.value);
		if (!open) {
			if (!manualPaused.value) {
				ctx.pause();
				manualPaused.value = true;
			}
		} else {
			if (manualPaused.value) {
				ctx.play();
				manualPaused.value = false;
			}
		}
	};

	// 视频控制逻辑
	const togglePlay = () => {
		const ctx = getVideoContext(current.value);
		if (manualPaused.value) {
			ctx.play();
			manualPaused.value = false;
		} else {
			ctx.pause();
			manualPaused.value = true;
		}
	};

	const onSwiperChange = (e) => {
		const newIndex = e.detail.current;
		// hint(current.value + ',' + e.detail.current);
		getVideoContext(current.value).pause();
		current.value = newIndex;
		commentPage.value = 1;
		loadStatus.value = true;
		commentCount.value = 0;

		setTimeout(() => {
			getVideoContext(newIndex).play();
		}, 300);

		if (videoList.value.length - newIndex < 4) {
			loadVideos();
		}

		overlay.value = true;

		setTimeout(() => {
			overlay.value = false;
		}, 2000);
	};

	// 视频上下文管理
	const getVideoContext = (index) => {
		if (!videoContexts[index]) {
			const videoId = `video-${index}`;
			videoContexts[index] = uni.createVideoContext(videoId);
		}
		return videoContexts[index];
	};

	const clearAllVideoContexts = () => {
		Object.values(videoContexts).forEach((ctx) => ctx.pause());
		videoContexts = {};
	};

	// 播放控制
	const playCurrentVideo = () => {
		getVideoContext(current.value).play();
	};

	const pauseCurrentVideo = () => {
		getVideoContext(current.value).pause();
	};

	// 数据加载
	const loadVideos = async () => {
		try {
			const res = await port('getVideoList');
			videoList.value = [...videoList.value, ...res.data];
		} finally {
		}
	};

	// // 视频结束处理
	// const onVideoEnd = async () => {
	// 	if (current.value < videoList.value.length - 1) {
	// 		current.value += 1;
	// 	} else {
	// 		await loadVideos();
	// 		current.value += 1;
	// 	}
	// };
</script>

<style scoped lang="scss">
	.touch-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;
	}

	.scroll-Y {
		height: calc(60vh);
	}
	// :deep(.u-transition){
	// 	z-index: 998 !important;
	// }

	.comment-text {
		padding: 30rpx;
		padding-top: 40rpx;

		.fill {
			background: #f6f6f6;
			border-radius: 20rpx;
			padding: 24rpx;
			.inp {
				font-weight: 400;
				font-size: 26rpx;
				color: #000;
				width: 100%;
				height: 120rpx;
			}
			.inp-place {
				font-weight: 400;
				font-size: 26rpx;
				color: #cccccc;
			}

			.images {
				flex-wrap: wrap;
			}
		}

		.fun-fill {
			margin-top: 20rpx;
			.icons {
				.icon {
					width: 40rpx;
					height: 42rpx;
					margin-left: 5rpx;
				}
			}
			.btn {
				font-weight: 500;
				font-size: 30rpx;
				color: #ffffff;
				width: 100%;
				height: 72rpx;
				background: linear-gradient(-90deg, #fb3204 0%, #fe7800 100%);
				border-radius: 34rpx;
				text-align: center;
				line-height: 72rpx;
			}
		}
	}

	.comment {
		padding: 30rpx;
		position: relative;
		.comment-list {
			position: relative;

			.item {
				border-bottom: 1rpx solid #eeeeee;
				padding: 36rpx 0;
				&:last-child {
					border-bottom: none;
				}
				.photo {
					width: 68rpx;
					height: 68rpx;
					border-radius: 50%;
				}
				.right {
					margin-left: 17rpx;
					.nickname {
						font-weight: 400;
						font-size: 22rpx;
						color: #888888;
						.author {
							margin-left: 9rpx;
							font-weight: 400;
							font-size: 22rpx;
							color: #ffffff;
							background: #fb3204;
							border-radius: 4rpx;
							padding: 2rpx 5rpx;
							height: 28rpx;
							line-height: 28rpx;
						}
					}
					.replay-nickname {
						font-weight: 400;
						font-size: 22rpx;
						color: #888888;
					}
					.replay-next {
						.icon {
							margin: 0 18rpx;
						}
					}
					.content {
						font-weight: 400;
						font-size: 26rpx;
						color: #333333;
						margin: 18rpx 0;
					}
					.images {
						margin: 18rpx 0;
						.ch {
							margin-right: 10rpx;
						}
					}
					.re-time {
						.time {
							font-weight: 400;
							font-size: 22rpx;
							color: #aaaaaa;
						}
						.replay {
							font-weight: 400;
							font-size: 22rpx;
							color: #666666;
							margin-left: 40rpx;
						}
					}
				}
			}
		}
		.replay-con {
			position: fixed;
			bottom: 0;
			width: calc(100% - 60rpx);
			padding: 17rpx 0;
			box-shadow: 0rpx -1rpx 0rpx 0rpx #eeeeee;
			background-color: #fff;
			.chn {
				background: #f6f6f6;
				border-radius: 36rpx;
				width: calc(100% - 48rpx);
				padding: 16rpx 24rpx;
				.tips {
					font-weight: 400;
					font-size: 26rpx;
					color: #cccccc;
				}
				.icons {
					.icon {
						width: 40rpx;
						height: 42rpx;
						margin-left: 36rpx;
					}
				}
			}
		}

		.comment-title {
			font-weight: 500;
			font-size: 34rpx;
			color: #000000;

			// margin-bottom: 40rpx;
			> text {
				font-size: 26rpx;
			}
		}
	}

	.swiper {
		height: calc(100vh - 114rpx);
		width: 100vw;
	}

	.video {
		width: 100%;
		height: 100%;
	}

	:deep(.uni-video-bar) {
		position: absolute;
		bottom: 0;
		height: 50rpx;
	}
	:deep(.uni-video-control-button) {
		width: 13rpx;
		height: 15rpx;
		padding: 16.5px 12.5px 14.5px 8.5px;
	}
	:deep(.uni-video-ball) {
		width: 11px;
		height: 11px;
		padding-top: 16.1px;
	}
	:deep(.uni-video-fullscreen) {
		width: 13px;
		height: 13px;
		padding-top: 16px;
	}

	.right-controls {
		position: absolute;
		right: 20rpx;
		bottom: calc(190rpx - 114rpx);
		color: white;

		.item {
			margin-top: 45rpx;
			.icon {
				width: 52rpx;
				height: 52rpx;
			}
			.val {
				font-weight: 400;
				font-size: 24rpx;
				color: #ffffff;
				margin-top: 6rpx;
			}
		}
	}

	.user-info {
		position: absolute;
		left: 20rpx;
		bottom: calc(190rpx - 114rpx);
		width: 454rpx;
		.user {
			.photo {
				width: 44rpx;
				height: 44rpx;
				border-radius: 50%;
			}
			.nickname {
				font-weight: 400;
				font-size: 20rpx;
				color: #ffffff;
				padding: 0 12rpx;
			}
			.date {
				font-weight: 400;
				font-size: 20rpx;
				color: #dcdbdb;
			}
		}

		.product {
			background: #ffffff;
			border-radius: 18rpx;

			padding: 4rpx;
			.icon {
				width: 96rpx;
				height: 96rpx;
				border-radius: 18rpx;
			}
			.right {
				margin-left: 10rpx;
				.title {
					font-weight: 400;
					font-size: 24rpx;
					color: #000000;
				}
				.price-box {
					align-items: end;
					.price {
						font-weight: 500;
						font-size: 32rpx;
						color: #fb3204;
					}
					.decoration {
						font-weight: 400;
						font-size: 20rpx;
						color: #999999;
						line-height: 38rpx;
						text-decoration-line: line-through;
						margin-left: 10rpx;
					}
				}
			}
		}

		.video-desc {
			margin: 24rpx 0;

			font-weight: 400;
			font-size: 26rpx;
			color: #ffffff;
		}
	}
</style>
